Page({
  data: {
    templateList: [],
    selectedTemplate: null,
    selectedIndex: 0,
    uploadProgress: 0,
    uploading: false,
    downloadUrl: '',
    isDownloading: false
  },

  onLoad() {
    this.getTemplateList();
  },

  getTemplateList() {
    const that = this;
    wx.request({
      url: 'https://mapp.scoringchina.com/interface/xijiuopen/upload/templist',
      method: 'GET',
      success(res) {
        if (res.data.errorcode.code === 'ok') {
          that.setData({
            templateList: res.data.data,
            selectedTemplate: res.data.data[0],
          });
        }
      },
      fail(err) {
        console.error('获取模板列表失败:', err);
      }
    });
  },
 // 上一张
 prevSlide() {
  if (this.data.selectedIndex > 0) {
    this.setData({
      selectedIndex: this.data.selectedIndex - 1
    });
  }
},

// 下一张
nextSlide() {
  if (this.data.selectedIndex < this.data.templateList.length - 1) {
    this.setData({
      selectedIndex: this.data.selectedIndex + 1
    });
  }
},

// 处理 swiper 的切换
onSwiperChange(e) {
  this.setData({
    selectedIndex: e.detail.current
  });
},

  onSwiperChange(e) {
    const index = e.detail.current;
    this.setData({
      selectedIndex: index,
      selectedTemplate: this.data.templateList[index]
    });
  },
  chooseVideo() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album'],
      maxDuration: 15,
      success: res => {
        const file = res.tempFiles[0];
        const tempFilePath = file.tempFilePath;
        // 检查视频大小(50MB = 50 * 1024 * 1024 bytes)
        if (file.size > 50 * 1024 * 1024) {
          wx.showToast({ 
            title: '视频大小不能超过50MB', 
            icon: 'none',
            duration: 3000
          });
          return;
        }
        if (file.duration > 15) {
          wx.showToast({ title: '视频时长不能超过15秒', icon: 'none' });
          return;
        }
  
        wx.getVideoInfo({
          src: tempFilePath,
          success: info => {
            const { width, height } = info;
  
            if (height <= width) {
              wx.showToast({ title: '请上传竖屏视频', icon: 'none' });
              return;
            }
  
            // 通过校验，上传
            this.uploadVideo(tempFilePath);
          },
          fail: err => {
            console.error('getVideoInfo 失败:', err);
            wx.showToast({
              title: '无法读取视频信息，请使用真机上传',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        console.error('chooseMedia 失败:', err);
      }
    });
  },


  // 重新上传方法
  reUpload() {
    this.setData({
      downloadUrl: '', // 清空下载链接
      uploadProgress: 0, // 重置上传进度
      uploading: false // 重置上传状态
    });
    
    // 直接调用选择视频方法
    // this.chooseVideo();
  },

// ... existing code ...
  uploadVideo(filePath) {
    const that = this;
    const user_id = getApp().globalData.userInfo.userID;

    that.setData({ uploading: true, uploadProgress: 0 });

    const uploadTask = wx.uploadFile({
      url: 'https://mapp.scoringchina.com/interface/xijiuopen/upload/uploadAndWatermark',
      filePath: filePath,
      name: 'video',
      formData: {
        tmp_url: that.data.selectedTemplate,
        user_id: user_id
      },
      success(res) {
        try {
          const jsonString = res.data.replace(/^\uFEFF/, '');
          const response = JSON.parse(jsonString);
          if (response.errorcode.code === 'ok' && response.data.downloadUrl) {
            that.setData({
              downloadUrl: response.data.downloadUrl
            });
          } else {
            wx.showToast({ title: '上传失败', icon: 'none' });
          }
        } catch (error) {
          console.error('解析失败:', error);
          wx.showToast({ title: '数据解析失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '上传失败', icon: 'none' });
      },
      complete() {
        that.setData({ uploading: false });
      }
    });

    uploadTask.onProgressUpdate(res => {
      that.setData({ uploadProgress: res.progress });
    });
  },

  downloadVideo() {
    const that = this;
    // 如果正在下载中，直接返回
    if (that.data.isDownloading) {
      return;
    }
    that.setData({
      isDownloading: true
    });

    const user_id = getApp().globalData.userInfo.userID;

    wx.downloadFile({
      url: that.data.downloadUrl,
      success(res) {
        wx.request({
          url: 'https://mapp.scoringchina.com/interface/xijiuopen/upload/download',
          method: 'GET',
          data: {
            user_id: user_id,
            downloadUrl: that.data.downloadUrl
          }
        });
        wx.saveVideoToPhotosAlbum({
          filePath: res.tempFilePath,
          success() {
            wx.showToast({ title: '保存成功', icon: 'success' });
          },
          fail() {
            wx.showToast({ title: '保存失败', icon: 'none' });
          },
          complete() {
            that.setData({
              isDownloading: false
            });
          }
        });
      },
      fail() {
        wx.showToast({ title: '下载失败', icon: 'none' });
        that.setData({
          isDownloading: false
        });
      }
    });
  }
});
